<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>让坦克开起来</title>
		<style type="text/css">
			input{font-size:26px;margin-top: 20px;}
			body{background-image: url(images/grassland.png);}
			#mytank{position: absolute;left:10px;top:100px}
		</style>
	</head>
	<body>		
		<img id="mytank" src="images/right.png"/>
		<script>
			// 189000561-朱一月
			let mytank = document.querySelector("#mytank");
			let leftmove = 10;//设置初始坦克左边距
			let topmove = 100;//设置初始位置坦克的上边距
			let current = 0;//默认旋转角度为0，坦克头朝右
			diaotou = function(){
				//一旦到达界面边界时进行提示并自动掉头
				alert("哎呀！没有路了呢！请换条路走吧！");
				mytank.style.transform = 'rotate('+(current+180)%360+'deg)';
			}
			change_x = (distence,angel) =>{
				//坦克向左/右移动distence距离
				leftmove += distence;
				mytank.style.left = leftmove + "px";
				//坦克向左/右移动时，坦克头始终朝向左/右
				current = angel;
				mytank.style.transform = 'rotate('+current%360+'deg)';	
			}
			change_y = (distence,angel) =>{
				//坦克向上/下移动distence距离
				topmove += distence;
				mytank.style.top = topmove + "px";
				//坦克向上/下移动时，坦克头始终朝向上/下
				current = angel;
				mytank.style.transform = 'rotate('+current%360+'deg)';	
			}		
			//添加禁止使用右键事件
			document.addEventListener('contextmenu', (e)=>{
				e.preventDefault();// 阻止默认事件
			})	
			//添加按键键盘监听事件
			document.addEventListener("keydown", (e) => {
				//按键“A 、方向键左键 、小键盘的4”坦克向左移动
				if(e.keyCode == 65 || e.keyCode == 37 || e.keyCode == 100){
					if(mytank.offsetLeft <= 0 ){//判断坦克是否到达左边界
						diaotou();
					}else{
						change_x(-5,180);
					}
				}
				//按键“W 、方向键上键 、小键盘的8”坦克向上移动
				else if(e.keyCode == 87 || e.keyCode == 38 || e.keyCode == 104){
					if(mytank.offsetTop <= 0 ){//判断坦克是否到达上边界
						diaotou();
					}else{
						change_y(-5,270);
					}	
				}
				//按键“D 、方向键右键 、小键盘的6”坦克向右移动
				else if(e.keyCode == 68 || e.keyCode == 39 || e.keyCode == 102){
					if (mytank.offsetLeft > 1536){//判断坦克是否到达右边界
						diaotou();
					}else{
						change_x(5,0);
					}	
				}
				//按键“S 、方向键下键 、小键盘的2”坦克向下移动
				else if(e.keyCode == 83 || e.keyCode == 40 || e.keyCode == 98){
					if(mytank.offsetTop > 762 ){//判断坦克是否到达下边界
						diaotou();
					}else{
						change_y(5,90);
					}							
				}
			});	
		</script>
	</body>
</html>


